import FileUtils from "../common/file_utils";
import convert from "xml-js";

let instance

/**
 * xml文件读取管理器，读取xml文件
 */
export default class XmlManager {
  constructor() {
    if (instance) return instance

    instance = this

    this.readXml()
  }

  readXml() {
    let xmlIntroduce = FileUtils.readFile("fgui/assets/Package1/scene_introduce_game.xml")
    let xmlSelectRoute = FileUtils.readFile("fgui/assets/Package1/scene_select_route.xml")
    let xmlStartGame = FileUtils.readFile("fgui/assets/Package1/scene_start_game.xml")
    let xmlMainGame = FileUtils.readFile("fgui/assets/Package1/scene_main.xml")
    this.sceneIntroduce = convert.xml2js(xmlIntroduce,{ compact: true, spaces: 4 })
    this.sceneSelectRoute = convert.xml2js(xmlSelectRoute,{ compact: true, spaces: 4 })
    this.sceneStartGame = convert.xml2js(xmlStartGame,{ compact: true, spaces: 4 })
    this.sceneMainGame = convert.xml2js(xmlMainGame,{ compact: true, spaces: 4 })
  }

  obtainAttributeByKey(objOrArr, keyName) {
    var value;
    if(Array.isArray(objOrArr)){
      objOrArr.forEach((v,i) =>{
        let attributes = v._attributes
        if(attributes.name === keyName){
          value = this.assetName(attributes.fileName)
          return value
        }
      })
    }else {
      value =  this.assetName(objOrArr._attributes.fileName);
    }
    return value
  }

  obtainAttributes(objOrArr, keyName) {
    var value ;
    if(Array.isArray(objOrArr)){
      objOrArr.forEach((v,i) =>{
        let attributes = v._attributes
        if(attributes.name === keyName){
          value = attributes
          return value
        }
      })
    }else {
      if(objOrArr._attributes.name === keyName){
        return  objOrArr._attributes;
      }

    }
    return value
  }
  assetName(fileName){
    return "fgui/assets/Package1/".concat(fileName)
  }

}

Object.assetName = function (fileName) {
  return "fgui/assets/Package1/".concat(fileName)
}